package com.eerl.pdev.data;

import com.eerl.pdev.MySettingsState;
import com.eerl.pdev.util.Notice;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;

import java.io.IOException;

public class OpenErlDataFile {
    public static void open(AnActionEvent e, String erlDataConfigPath) {
        // wps et.exe
        String wpsEtExePath = MySettingsState.getInstance().WPS_ET_EXE_ABS_PATH;
        if (wpsEtExePath.isBlank() || erlDataConfigPath.isBlank()) {
            Notice.showNotification(e, "data path or wps et path is empty, please check config", NotificationType.ERROR);
            return;
        }
        // 获取当前项目
        Project project = e.getProject();
        if (project == null) {
            throw new RuntimeException("exec [TerminalActionMakeThis] project is null");
        }
        // 获取当前打开的文件
        VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
        if (virtualFile == null) {
            Notice.popMessage(e, "No file is currently open");
            return;
        }
        if (virtualFile.getName().endsWith("_data.erl")) {
            try {
                Runtime.getRuntime().exec(String.format("\"%s\" %s\\%s.xml", wpsEtExePath, erlDataConfigPath, virtualFile.getNameWithoutExtension()));
            } catch (IOException ex) {
                throw new RuntimeException("exec open local data config err", ex);
            }
        } else {
            Notice.showDialogMessage("Erl Data Open Fail", "this file is not endwith _data.erl");
        }
    }
}
